package com.brother.template.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.*;

import java.io.File;

/**
 * 配置 静态资源加载的路径
 * 跨域CORS配置
 * 某些请求不要拦截
 *
 * @author xjwtt
 * @date 2018/8/21
 */
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 加载的静态资源路径
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String templatesPath = System.getProperty("user.dir") + "/" + "templates/";
        String staticPath = System.getProperty("user.dir") + "/" + "static/";
        File templatesFile = new File(templatesPath);
        File staticFile = new File(staticPath);
        if (templatesFile.exists()) {
            registry.addResourceHandler("/**").addResourceLocations("file:" + templatesPath);

        } else {
            registry.addResourceHandler("/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/templates/");
        }

        if (staticFile.exists()) {
            registry.addResourceHandler("/**").addResourceLocations("file:" + staticPath);

        } else {
            registry.addResourceHandler("/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/");

        }
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 跨域CORS设置
     *
     * @param registry
     */
    @Override
    //重写父类提供的跨域请求处理的接口
    public void addCorsMappings(CorsRegistry registry) {
        //添加映射路径
        registry.addMapping("/**")
                .allowedHeaders("*")
                //是否发送Cookie信息
                .allowCredentials(true)
                //放行哪些原始域(请求方式)
                .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
                //放行哪些原始域
                .allowedOrigins("*")
                //放行哪些原始域(头部信息)
                .allowedHeaders("*");
    }

}
